<template>
  <!-- tl -->
  <section>
    <div>
      <label>体检次数：</label>
      <el-select style="width:120px;" @change="changeNum" v-model="form.num" placeholder="体检次数">
        <el-option v-for="(item,index) in nums" :key="index" :value="item" :label="item"></el-option>
      </el-select>
      <!-- <el-select style="margin-left:10px;" v-model="form.num" placeholder="体检医生">
        <el-option v-for="(item,index) in doctorList" :key="index" :label="item"></el-option>
      </el-select>-->
      <el-button :loading="addLoading" @click="addExam()" style="margin-left:20px;">新增体检记录</el-button>
      <el-button v-show="form.num <= count" style="margin-left:20px;" @click="doPrint()">打印</el-button>
    </div>
    <div class="baby_examination_box">
      <h4 class="examin_title">
        体格检查
        <el-button @click="keep()" :loading="btnLoading" class="btn_examin">保存</el-button>
      </h4>
      <div class="baby_inspect_info">
        <el-row>
          <el-col class="baby-item" :span="8">
            <span class="attr_name">体检日期：</span>
            <el-date-picker
              v-model="form.tjDate"
              :appendToBody="false"
              type="date"
              class="baby-date_control"
              @change="getMonth()"
              value-format="yyyy/MM/dd"
              placeholder="选择日期"
            ></el-date-picker>
          </el-col>
          <el-col class="baby-item" :span="8">
            <span class="attr_name">体检月龄：</span>
            <el-select filterable class="baby-date_control" v-model="form.ageMonth">
              <el-option v-for="i in 216" :key="i" :value="i" :label="i"></el-option>
            </el-select>
            <!-- <el-date-picker
              v-model="form.ageMonth"
              type="date"
              class="baby_control"
              value-format="yyyy/MM/dd"
              placeholder="选择日期"
            ></el-date-picker>-->
          </el-col>
          <el-col v-for="(item,index) in infoList" :key="index" class="baby-item" :span="8">
            <span class="attr_name">
              <span style="color:#ff4400" v-if="item.isRequire=='T'">*</span>
              {{item.attrName}}：
            </span>
            <el-date-picker
              v-if="item.attrType=='DATE'"
              v-model="item.values"
              type="date"
              class="baby-date_control"
              value-format="yyyy/MM/dd"
              placeholder="选择日期"
            ></el-date-picker>
            <!-- <el-input v-if="item.attrType=='TEXT'" class="baby_control" v-model="item.values">
              <template v-if="item.attrUnit!==''" slot="append">{{item.attrUnit}}</template>
            </el-input>-->
            <el-input
              class="baby_control"
              v-if="(item.attrCode=='1000030050' || item.attrCode =='1000030051' || item.attrCode=='1000030052' || item.attrCode =='1000030006' || item.attrCode=='1000030003') && item.attrType=='TEXT'"
              v-model="item.values"
              :disabled="true"
              placeholder="请输入内容"
            ></el-input>
            <el-input
              class="baby_control"
              v-if="(item.attrCode!=='1000030050' && item.attrCode !=='1000030051' && item.attrCode !=='1000030052' && item.attrCode !=='1000030004'&& item.attrCode !=='1000030005'&& item.attrCode !=='1000030007' && item.attrCode !=='1000030006' && item.attrCode!='1000030003')&& item.attrType=='TEXT'"
              v-model="item.values"
              placeholder="请输入内容"
            >
              <template v-if="item.attrUnit!==''" slot="append">{{item.attrUnit}}</template>
            </el-input>
            <el-input
              class="baby_control"
              v-if="(item.attrCode=='1000030005') && item.attrType=='TEXT'"
              @blur="getEvaluate(1,$event);"
              v-model="item.values"
              placeholder="请输入体检体重"
            >
              <template v-if="item.attrUnit!==''" slot="append">{{item.attrUnit}}</template>
            </el-input>
            <!--//体检体重-->
            <el-input
              class="baby_control"
              v-if="(item.attrCode=='1000030004')&& item.attrType=='TEXT'"
              @blur="getEvaluate(0,$event);"
              v-model="item.values"
              placeholder="请输入体检身高"
            >
              <template v-if="item.attrUnit!==''" slot="append">{{item.attrUnit}}</template>
            </el-input>
            <!--//体检身高-->
            <el-input
              class="baby_control"
              v-if="(item.attrCode=='1000030007')&& item.attrType=='TEXT' "
              @blur="getEvaluate(2,$event);"
              v-model="item.values"
              placeholder="请输入体检头围"
            >
              <template v-if="item.attrUnit!==''" slot="append">{{item.attrUnit}}</template>
            </el-input>
            <!--//体检头围-->

            <el-input
              v-if="item.attrType=='TEXTAREA'"
              type="textarea"
              class="baby_control baby_control_textarea"
              maxlength="200"
              show-word-limit
              v-model="item.values"
            ></el-input>
            <el-select v-if="item.attrType=='SELECT'" class="baby_control" v-model="item.values">
              <el-option
                v-for="(i,index) in item.attrValue"
                :key="index"
                :label="i.valValue"
                :value="i.valKey"
              ></el-option>
            </el-select>
            <el-select
              v-if="item.attrType=='SELECT_TEXT'"
              class="baby_control"
              filterable
              allow-create
              default-first-option
              v-model="item.values"
            >
              <el-option
                v-for="(i,index) in item.attrValue"
                :key="index"
                :label="i.valValue"
                :value="i.valValue"
              ></el-option>
            </el-select>
          </el-col>
          <!-- <el-col class="baby-item" :span="8">
            <span>体检身高：</span>
            <el-input class="baby_control" v-model="form.height"></el-input>
          </el-col>
          <el-col class="baby-item" :span="8">
            <span>龋齿：</span>
            <el-input class="baby_control" placeholder="请输入内容" v-model="form.ynum">
              <template slot="append">颗</template>
            </el-input>
          </el-col>-->
        </el-row>
      </div>
      <iframe
        v-show="showReport"
        frameborder="0"
        height="0px"
        width="0px"
        ref="iframe"
        src="/print/Examinreport.html"
      ></iframe>
    </div>
    <el-dialog
      title="选择打印项目"
      :visible="printVisible"
      :append-to-body="true"
      @close="printVisible = false"
    >
      <el-form>
        <el-form-item label="检查项目：">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleAllChange"
          >全选</el-checkbox>
          <el-checkbox-group v-model="checkProject" @change="handleChecked">
            <el-checkbox
              v-for="examin in examinList"
              :label="examin.id"
              style="width:200px;"
              :key="examin.id"
            >{{examin.attrName}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="printVisible = false">取 消</el-button>
        <el-button type="primary" @click="doPrint()">确 定</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>
export default {
  props: ["detail", "ispersonal"],
  name: "",
  data() {
    return {
      doctorList: [],
      numList: [],
      form: {
        tjDate: "",
        ageMonth: "",
        ageView: "",
        num: 1,
      },
      peId: "",
      addLoading: false,
      btnLoading: false,
      infoList: [],
      oldList: [],
      printList: [],
      print: [],
      nums: 0,
      count: 0,
      showReport: false,
      iframe: "",
      flog: 0,
      bmiTips: "",
      showNums: false,
      isChange: false,
      printVisible: false,
      isIndeterminate: false,
      checkProject: [],
      checkAll: [],
      examinList: [],
      isFirst: false,
      isSubmit: false,
      firstNum: 0,
    };
  },
  mounted() {
    let th = this;
    th.iframe = th.$refs.iframe.contentWindow;
    th.findListByCategoryId();
    th.getExaminNums();
    th.form.tjDate = th.getChildDate();
  },
  watch: {
    infoList: {
      deep: true,
      handler: function (n, o) {
        let th = this;
        th.flog++;
        th.firstNum++;
        if (th.flog > 1) {
          if (th.firstNum >= 2) {
            th.isChange = false;
            th.$emit("isChangeValue", th.isChange);
          }
        }
      },
    },
  },
  methods: {
    //获取类目
    findListByCategoryId() {
      let th = this;
      th.showLoading();
      th.$api
        .findListByCategoryId({ isOnlyRoot: "T", categoryId: "1000030000" })
        .then((res) => {
          if (res.executed) {
            let list = res.infos;
            th.form.ageMonth = th.detail.ageMonth;
            list.map((it, index) => {
              if (it.attrType == "SELECT")
                if (it.attrValue != undefined && it.attrValue.length > 0) {
                  it.values = it.attrValue[0].valValue;
                } else {
                  it.values = "";
                }
            });
            th.showLoading(false);
            th.isFirst = true;
            th.firstNum = 0;
            th.infoList = list;
            th.oldList = list;
          }
        }).catch(error=>{
          this.$message.error("获取体检类目失败，请联系工作人员");
          this.showLoading(false);
        });

      //获取打印类目
      //1000160004  第一版打印    1000160005第二版打印
      th.$api
        .findListByCategoryId({ isOnlyRoot: "T", categoryId: "1000160005" })
        .then((res) => {
          if (res.executed) {
            let list = res.infos;
            let data = [];
            for (let i = 0; i < list.length; i++) {
              let arr = {};
              Object.assign(arr, list[i]);
              if (arr.attrType == "SELECT") {
                if (arr.attrValue) {
                  if (arr.attrValue.length > 0) {
                    arr.values = arr.attrValue[0].valValue;
                  }
                }
              } else {
                arr.values = "";
              }
              data.push(arr);
              th.showLoading(false);
            }
            th.printList = data;
          }
        }).catch(error=>{
          this.$message.error("获取体检类目2失败，请联系工作人员");
          this.showLoading(false);
        });
    },
    //获取体检次数
    getExaminNums() {
      let th = this;
      let fn = async function () {
        let numbers = 0;
        numbers = await th.getExaminCount();
        if (numbers) {
          if (numbers < 1) {
            th.count = 1;
            th.nums = 1;
            th.form.num = 1;
          } else {
            th.count = Number(numbers);
            th.nums = Number(numbers);
            let nums = Number(th.nums) + 1;
            th.form.num = th.nums;
            th.changeNum(th.count);
          }
        }
      };
      fn();
    },
    //获取次数
    getExaminCount() {
      const th = this;
      return new Promise(function (s, e) {
        th.$api
          .getExaminationNums({ patientId: th.detail.patientId, sort: "F" })
          .then((res) => {
            if (res.executed) {
              s(res.infos.length);
            } else {
              e(res.message);
            }
          }).catch(error=>{
            this.$message.error("获取体检次数，请联系工作人员");
            this.showLoading(false);
          });
      });
    },
    //保存体检
    keep() {
      let th = this;
      let data = th.infoList;
      // let values = [];
      let isBos = th.saveInfoValues(data);
      if (typeof isBos == "boolean") {
        th.$message.warning("请填写所有带*号的检查项");
      } else {
        let values = th.saveInfoValues(data);
        let json = { categoryId: "1000160002", peId: "" };
        json.ageMonth = th.form.ageMonth;
        json.date = th.form.tjDate;
        json.patientId = th.detail.patientId; //患者id
        json.archivesId = "-1";
        json.values = "";
        json.createPersonId = th.adminUser.memberId;
        json.peId = th.peId;
        th.btnLoading = true;
        json.values = JSON.stringify(values);
        th.$api.insertPhysicalExamination(json).then((res) => {
          if (res.executed) {
            th.$message.success("保存成功");
            th.btnLoading = false;
            th.isSubmit = true;
            th.firstNum = 0;
            let fn = async function () {
              let numbers = 0;
              numbers = await th.getExaminCount();
              if (numbers) {
                th.count = Number(numbers);
                th.nums = Number(numbers);
                th.changeNum();
                th.$emit("submit");
              }
            };
            fn();
          } else {
            th.$message.error(res.message);
            th.btnLoading = false;
          }
        });
      }
    },
    changeNum(num) {
      let th = this;
      let nums = 0;
      if (num != undefined) {
        nums = num;
      } else {
        nums = th.form.num;
      }
      th.isFirst = true;
      if (nums <= th.count) {
        th.infoList = th.oldList;
        th.$api
          .getExaminationNums({
            patientId: th.detail.patientId,
            nums: nums,
            isOnlyRoot: "F",
          })
          .then((res) => {
            if (res.executed) {
              if (res.infos.length > 0) {
                let infos = res.infos[0];
                th.peId = infos.id;
                th.form.ageMonth = infos.ageMonth;
                th.form.ageView = infos.ageView;
                th.form.tjDate = infos.date;
                let data = infos.values;
                let info = th.infoList;
                let print = th.printList;
                let infoList = [];
                th.infoList = th.getExaminInfo(info, data);
                th.print = th.getExaminInfo(print, data);
                th.isFirst = true;
                th.firstNum = 0;
                // th.getMonth();
              }
            }
          });
      } else {
        th.infoList = th.oldList;
        th.form.tjDate = th.getChildDate();
        th.isFirst = true;
        th.peId = "";
        th.firstNum = 0;
        th.getMonth();
      }
    },
    handleChecked(value) {
      let th = this;
      let checkedCount = value.length;
      th.checkAll = checkedCount === th.examinList.length;
      th.isIndeterminate =
        checkedCount > 0 && checkedCount < th.examinList.length;
    },
    handleAllChange(val) {
      let th = this;
      let checked = [];
      for (var i = 0; i < th.examinList.length; i++) {
        checked.push(th.examinList[i].id);
      }
      th.checkProject = val ? checked : [];
      th.isIndeterminate = false;
    },
    getPrintExamin() {
      let th = this;
      let list = th.print;
      let examinList = [];
      let check = [];
      examinList = list.filter((it, index) => {
        if (index > 6 && index < 36) {
          check.push(it.id);
          return it;
        }
      });
      th.checkProject = check;
      th.isIndeterminate = true;
      th.examinList = examinList;
      th.printVisible = true;
    },
    doPrint() {
      let th = this;
      let basiList = [];
      let left_eye = "";
      let right_eye = "";
      let left_ear = "";
      let right_ear = "";
      let zd = "";
      let syans = "";
      let bmiTips = "";
      let height = "";
      let weight = "";
      let bmi = "";
      let zhpj = "";
      let fzjc = "";
      let motion = "";
      let spirit = "";
      let list = th.print;
      let info = th.infoList;
      let isSys = false;
      let isZd = false;
      let isSpirit = false;
      let cproject = th.checkProject;
      let isCeil = true;
      let exList = [];

      list.forEach((it, index) => {
        if (index > 6 && index < 34) {
          if (it.id == "1000150118") {
            isSys = true;
          } else if (it.id == "1000150149") {
            isZd = true;
          } else if (it.id == "1000150114" || it.id == "1000150115") {
            isSpirit = true;
          } else {
            exList.push(it);
          }
        }
      });
      let num = Math.ceil(Number(exList.length) / 2);
      if (Number(exList.length) % 2 == 0) {
        isCeil = false;
      } else {
        isCeil = true;
      }
      num = Number(num * 8);
      basiList = list.filter((it, index) => {
        if (index < 7) {
          return it;
        }
      });
      info.filter((it, index) => {
        if (it.id == "1000150152") {
          let v = Number(it.values);
          if (typeof v == "number") {
            left_eye = it.values2;
          } else {
            left_eye = it.values;
          }
        }
        if (it.id == "1000150153") {
          let v = Number(it.values);
          if (typeof v == "number") {
            right_eye = it.values2;
          } else {
            right_eye = it.values;
          }
        }
        if (it.id == "1000150150") {
          let v = Number(it.values);
          if (typeof v == "number") {
            left_ear = it.values2;
          } else {
            left_ear = it.values;
          }
        }
        if (it.id == "1000150151") {
          let v = Number(it.values);
          if (typeof v == "number") {
            right_ear = it.values2;
          } else {
            right_ear = it.values;
          }
        }
        if (it.id == "1000150149") {
          zd = it.values;
        }
        if (it.id == "1000150118") {
          syans = it.values;
        }
        if (it.id == "1000030004") {
          height = it.values;
        }
        if (it.id == "1000030005") {
          weight = it.values;
        }
        if (it.id == "1000150114") {
          spirit = it.printvalue;
        }
        if (it.id == "1000150115") {
          motion = it.printvalue;
        }
        if (it.id == "1000030006") {
          bmiTips = it.values;
        }
        if (it.id == "1000150112") {
          zhpj = it.values;
        }
        if (it.id == "1000150154") {
          fzjc = it.values;
        }
      });
      if (height != "" && weight != "") {
        let h = Number(height / 100).toFixed(2);
        bmi = Number(weight) / Number(h * h);
        bmi = bmi.toFixed(2);
      }
      if (th.form.tjDate) {
        th.form.tjDate = th.form.tjDate.replace(/\//g, "-");
      }
      th.iframe.postMessage(
        {
          cmd: "postJson",
          params: JSON.stringify({
            signForm: basiList,
            logo: th.adminUser.printLogo,
            detail: th.detail,
            infos: exList,
            leftEye: left_eye,
            rightEye: left_eye,
            leftEar: left_ear,
            rightEar: right_ear,
            zd: zd,
            syans: syans,
            bmi: bmiTips,
            ageView: th.form.ageView,
            spirit: spirit,
            motion: motion,
            tjDate: th.form.tjDate,
            zhpj: zhpj,
            tjHeight: num,
            fzjc: fzjc, //辅助检查
            isSpirit: isSpirit,
            isCeil: isCeil, //单双数
            isZd: isZd, //指导
            isSys: isSys, //实验室
            hospitalName: th.adminUser.hospitalName,
          }),
        },
        "*"
      );
      th.showReports = true;
    },
    getEvaluate(type, $event) {
      let th = this;
      if (th.form.ageMonth == "") {
        th.$message.error("请选择儿童当前体检月龄！");
        return false;
      }
      if ($event.target.value) {
        th.showLoading();
        th.$api
          .findChildTips({
            type: type,
            month: th.form.ageMonth,
            values: $event.target.value,
            sex: th.detail.sex == 1 ? "MAN" : "WOMEN",
            patientId: th.detail.patientId,
            whoType: 1,
          })
          .then((res) => {
            if (res.executed == true) {
              let info = th.infoList;
              info.map((it) => {
                //身高
                if (it.attrCode == "1000030050" && type == 0) {
                  it.values = res.tips;
                  it.value = res.tips;
                  it.printvalue = res.tips;
                }
                //体重
                if (it.attrCode == "1000030051" && type == 1) {
                  it.values = res.tips;
                  it.value = res.tips;
                  it.printvalue = res.tips;
                }
                //头围
                if (it.attrCode == "1000030052" && type == 2) {
                  it.values = res.tips;
                  it.value = res.tips;
                  it.printvalue = res.tips;
                }
              });
              th.infoList = info;
              th.showLoading(false);
              th.computeBmi();
            } else {
              th.showLoading(false);
              // th.$message.error(res.message);
            }
          })
          .catch((error) => {
            th.showLoading(false);
          });
      } else {
        // this.$emit("change",false)
      }
    },
    computeBmi() {
      let th = this;
      let bmi_width = 0;
      let bmi_height = 0;
      let bmi = 0;
      th.infoList.map((it) => {
        if (it.attrCode == "1000030005" && it.values != "") {
          //体重
          bmi_width = it.values;
        }
        if (it.attrCode == "1000030004" && it.values != "") {
          //身高
          bmi_height = it.values;
        }
        if (bmi_height != 0 && bmi_width != 0) {
          if (bmi_height > 10) {
            let b_heights = bmi_height / 100;
            bmi = bmi_width / (b_heights * b_heights).toFixed(2);
          }
        }
      });
      if (bmi == 0 || bmi_height == 0) {
      } else {
        //bmi
        th.showLoading();
        th.$api
          .findChildTips({
            month: bmi_height,
            values: bmi_width,
            patientId: th.detail.patientId,
            whoType: 1,
            sex: th.detail.sex == 1 ? "MAN" : "WOMEN",
            type: "3",
          })
          .then((res) => {
            if (res.success == true && res.executed == true) {
              th.infoList.filter((item) => {
                if (item.id == "1000030006") {
                  item.values = res.tips;
                }
              });
              th.showLoading(false);
            } else {
              th.showLoading(false);
            }
          })
          .catch((error) => {
            th.showLoading(false);
          });
      }
    },
    //新增体检记录
    addExam() {
      let th = this;
      th.form.tjDate = th.getChildDate();
      th.infoList = th.oldList;
      th.peId = "";
      th.nums = Number(th.nums) + 1;
      th.form.num = th.nums;
      th.addLoading = true;
      //体检记录
      th.firstNum = 0;
      th.getMonth();
    },
    getMonth() {
      let th = this;
      let tjDate = th.form.tjDate;
      let birth = th.detail.birthday;
      birth = birth.replace(/-/g, "/");
      th.$api
        .getMonthByExamination({ birth: birth, pxDate: tjDate })
        .then((res) => {
          if (res.executed) {
            th.form.ageMonth = Number(res.month);
            th.addLoading = false;
          } else {
            th.addLoading = true;
          }
        })
        .catch((error) => {
          th.addLoading = true;
        });
    },
  },
};
</script>
<style lang="scss" scoped>
.baby_examination_box {
  border: 1px solid #e7e7e7;
  padding-bottom: 20px;
  margin-top: 20px;
  .examin_title {
    background-color: #f8f8f8;
    font-size: 14px;
    text-align: left;
    padding: 16px 15px;
    border-bottom: 1px solid #e7e7e7;
  }
  .btn_examin {
    padding: 8px 12px;
    margin-top: -3px;
    background-color: #1ab394;
    color: #fff;
    border: 0px;
    float: right;
  }
}
.baby_inspect_info {
  // border:1px solid #e7e7e7;
  margin-top: 20px;
  .baby-item {
    display: flex;
    // display: inline-block;
    padding-right: 20px;
    margin-bottom: 10px;
    .attr_name {
      width: 140px;
      min-width: 140px;
      flex: 1;
      line-height: 36px;
      text-align: right;
    }
    .baby_control {
      flex: 2;
      display: contents;
      /deep/ .el-input-group__append {
        padding: 0;
        width: 60px;
        text-align: center;
        line-height: 34px;
      }
    }
    .baby-date_control {
      flex: 2;
    }
  }
}
</style>